var girl = 'img/head/girl.jpg';
var boy = 'img/head/boy.jpg';

var ul = document.getElementById('list');
var lis = [];
for (var i = 0; i < list.length; i++) {
  var img = list[i].gender == 1 ? `<img src="${boy}">` : `<img src="${girl}">`;
  var li =
    `<li>
                 <div class="head-img">${img}</div>    
                 <p>${list[i].name}</p>
                 <div class="cover"></div>
             </li>`;
  lis.push(li);
}
ul.innerHTML = lis.join("");

var btnBegin = document.getElementById('btn-begin');
var btnEnd = document.getElementById('btn-end');

//幸运用户
var targetName = document.getElementById('targetName');
var targetHead = document.getElementById('targetHead');

var timerId = null;
var rand = null;

// 开始
btnBegin.onclick = function() {
  btnBegin.style.display = 'none'
  var lis = ul.getElementsByTagName('li');
  if (timerId) {
    clearInterval(timerId);
  }
  var player = document.querySelector('#test');

  player.play();

  timerId = setInterval(function() {
    rand = getRandom(0, list.length - 1);
    targetName.innerHTML = list[rand].name;
    targetHead.src = list[rand].gender == 1 ? boy : girl;
    for (var i = 0; i < lis.length; i++) {
      // lis[i].children[2].className = 'cover';
      lis[i].children[2].classList.remove('active');
      if (i == rand) {
        // lis[i].children[2].className = 'cover active';
        lis[i].children[2].classList.add('active');
      }
    }
  }, 100);
  //结束
  player.addEventListener('ended', function() {


    if (timerId) {
      btnBegin.style.display = 'block'
      // btnBegin.style.textAlign= "center"
      targetName.innerHTML = list[rand].name;
      targetHead.src = list[rand].gender == 1 ? boy : girl;
      var url =
        "http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&text=" +
        encodeURI('恭喜' + list[rand].name + '被点到'); // baidu
      var n = null;
      n = new Audio(url);
      n.src = url;
      n.play();
      clearInterval(timerId);
    }
  }, false);

}
//结束
// btnEnd.onclick = function () {

//     if (timerId) {
//         targetName.innerHTML = list[rand].name;
//         targetHead.src = list[rand].gender == 1 ? boy : girl;
//         clearInterval(timerId);
//     }
// }

// 生成指定范围的随机整数
function getRandom(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
